package cn.otrue.patienthealthmanager.view;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.otrue.patienthealthmanager.R;
import cn.otrue.patienthealthmanager.bean.CityModel;
import cn.otrue.patienthealthmanager.bean.DistrictModel;
import cn.otrue.patienthealthmanager.bean.ProvinceModel;
import cn.otrue.patienthealthmanager.service.XmlParserHandler;
import cn.otrue.patienthealthmanager.utils.CommonUtil;
import cn.otrue.patienthealthmanager.view.kankan.wheel.widget.ArrayWheelAdapter;
import cn.otrue.patienthealthmanager.view.kankan.wheel.widget.OnWheelChangedListener;
import cn.otrue.patienthealthmanager.view.kankan.wheel.widget.WheelView;

import com.mhealth37.open.sdk.MhealthApplication;

public class CopyOfAscertainPopupWindow extends PopupWindow implements
		OnClickListener, OnWheelChangedListener {
	private MhealthApplication mhealthApp;
	private Context mContext;
	private View mPopView;
	private int textSize;
	private Activity activity;
	private boolean isComplete = false;
	private WheelView mViewProvince;
	private WheelView mViewCity;
	private WheelView mViewDistrict;
	private TextView mBtnConfirm;
	private TextView iv_catt_lastMonth;

	/**
	 * 所有省
	 */
	protected String[] mProvinceDatas;
	/**
	 * key - 省 value - 市
	 */
	protected Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
	/**
	 * key - 市 values - 区
	 */
	protected Map<String, String[]> mDistrictDatasMap = new HashMap<String, String[]>();

	/**
	 * key - 区 values - 邮编
	 */
	protected Map<String, String> mZipcodeDatasMap = new HashMap<String, String>();

	/**
	 * 当前省的名称
	 */
	protected String mCurrentProviceName;
	/**
	 * 当前市的名称
	 */
	protected String mCurrentCityName;
	/**
	 * 当前区的名称
	 */
	protected String mCurrentDistrictName = "";

	/**
	 * 当前区的邮政编码
	 */
	protected String mCurrentZipCode = "";

	/**
	 * 解析省市区的XML数据
	 */

	protected void initProvinceDatas() {
		List<ProvinceModel> provinceList = null;
		AssetManager asset = mContext.getAssets();
		try {
			InputStream input = asset.open("province_data.xml");
			// 创建一个解析xml的工厂对象
			SAXParserFactory spf = SAXParserFactory.newInstance();
			// 解析xml
			SAXParser parser = spf.newSAXParser();
			XmlParserHandler handler = new XmlParserHandler();
			parser.parse(input, handler);
			input.close();
			// 获取解析出来的数据
			provinceList = handler.getDataList();
			// */ 初始化默认选中的省、市、区
			if (provinceList != null && !provinceList.isEmpty()) {
				mCurrentProviceName = provinceList.get(0).getName();
				List<CityModel> cityList = provinceList.get(0).getCityList();
				if (cityList != null && !cityList.isEmpty()) {
					mCurrentCityName = cityList.get(0).getName();
					List<DistrictModel> districtList = cityList.get(0)
							.getDistrictList();
					mCurrentDistrictName = districtList.get(0).getName();
					mCurrentZipCode = districtList.get(0).getZipcode();
				}
			}
			// */
			mProvinceDatas = new String[provinceList.size()];
			for (int i = 0; i < provinceList.size(); i++) {
				// 遍历所有省的数据
				mProvinceDatas[i] = provinceList.get(i).getName();
				List<CityModel> cityList = provinceList.get(i).getCityList();
				String[] cityNames = new String[cityList.size()];
				for (int j = 0; j < cityList.size(); j++) {
					// 遍历省下面的所有市的数据
					cityNames[j] = cityList.get(j).getName();
					List<DistrictModel> districtList = cityList.get(j)
							.getDistrictList();
					String[] distrinctNameArray = new String[districtList
							.size()];
					DistrictModel[] distrinctArray = new DistrictModel[districtList
							.size()];
					for (int k = 0; k < districtList.size(); k++) {
						// 遍历市下面所有区/县的数据
						DistrictModel districtModel = new DistrictModel(
								districtList.get(k).getName(), districtList
										.get(k).getZipcode());
						// 区/县对于的邮编，保存到mZipcodeDatasMap
						mZipcodeDatasMap.put(districtList.get(k).getName(),
								districtList.get(k).getZipcode());
						distrinctArray[k] = districtModel;
						distrinctNameArray[k] = districtModel.getName();
					}
					// 市-区/县的数据，保存到mDistrictDatasMap
					mDistrictDatasMap.put(cityNames[j], distrinctNameArray);
				}
				// 省-市的数据，保存到mCitisDatasMap
				mCitisDatasMap.put(provinceList.get(i).getName(), cityNames);
			}
		} catch (Throwable e) {
			e.printStackTrace();
		} finally {

		}
	}

	public CopyOfAscertainPopupWindow(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public CopyOfAscertainPopupWindow(Activity activity,
			final GetPickResultListener getPickResultListener) {

		super(activity);
		this.activity = activity;
		mContext = activity;
		LayoutInflater inflater = (LayoutInflater) mContext
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mPopView = inflater.inflate(R.layout.activity_riqi, null);
		setUpViews();
		setUpListener();
		setUpData();
		textSize = CommonUtil.dip2px(mContext, 20);

		initWindowStyleByVersion(mPopView);

		// 设置SelectPicPopupWindow的View
		this.setContentView(mPopView);
		// 设置SelectPicPopupWindow弹出窗体的宽
		this.setWidth(LayoutParams.MATCH_PARENT);
		// 设置SelectPicPopupWindow弹出窗体的高
		this.setHeight(LayoutParams.WRAP_CONTENT);
		// 设置SelectPicPopupWindow弹出窗体可点击
		this.setFocusable(false);
		// 设置SelectPicPopupWindow弹出窗体动画效果
		this.setAnimationStyle(R.style.AnimBottom);
		this.setOutsideTouchable(true);

		mBtnConfirm.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub

				getPickResultListener.onGetResult(new Object[] {
						mCurrentProviceName, mCurrentCityName,
						mCurrentDistrictName }, 1);

				dismiss();
			}
		});

		iv_catt_lastMonth.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub

				dismiss();
			}
		});
	}

	private void initWindowStyleByVersion(View mPopView2) {
		// 窗口标题容器
		RelativeLayout rl_catt_popTitle = (RelativeLayout) mPopView2
				.findViewById(R.id.rl_catt_popTitle);
		// 窗口标题
		TextView tv_catt_windowTitle = (TextView) mPopView2
				.findViewById(R.id.tv_catt_windowTitle);
		Log.e("aaaaaa", (tv_catt_windowTitle == null) + "");
		// int dip2px = dip2px(mContext, 18);
		rl_catt_popTitle.setBackgroundColor(mContext.getResources().getColor(
				R.color.window_bg_children));
		tv_catt_windowTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
		// tv_catt_cancle.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);

	}

	private void setUpViews() {
		mViewProvince = (WheelView) mPopView.findViewById(R.id.id_province);
		mViewCity = (WheelView) mPopView.findViewById(R.id.id_city);
		mViewDistrict = (WheelView) mPopView.findViewById(R.id.id_district);
		mBtnConfirm = (TextView) mPopView.findViewById(R.id.btn_confirm);
		iv_catt_lastMonth = (TextView) mPopView
				.findViewById(R.id.iv_catt_lastMonth);
	}

	private void setUpListener() {
		// 锟斤拷锟絚hange锟铰硷拷
		mViewProvince.addChangingListener(this);
		// 锟斤拷锟絚hange锟铰硷拷
		mViewCity.addChangingListener(this);
		// 锟斤拷锟絚hange锟铰硷拷
		mViewDistrict.addChangingListener(this);
		// 锟斤拷锟給nclick锟铰硷拷
		mBtnConfirm.setOnClickListener(this);
		iv_catt_lastMonth.setOnClickListener(this);
	}

	private void setUpData() {
		initProvinceDatas();
		mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(mContext,
				mProvinceDatas));
		// 锟斤拷锟矫可硷拷锟斤拷目锟斤拷锟斤
		mViewProvince.setVisibleItems(7);
		mViewCity.setVisibleItems(7);
		mViewDistrict.setVisibleItems(7);
		updateCities();
		updateAreas();
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		// case R.id.btn_confirm:
		// showSelectedResult();
		// break;

		default:
			break;
		}
	}

	private void updateCities() {
		int pCurrent = mViewProvince.getCurrentItem();
		mCurrentProviceName = mProvinceDatas[pCurrent];
		String[] cities = mCitisDatasMap.get(mCurrentProviceName);
		if (cities == null) {
			cities = new String[] { "" };
		}
		mViewCity
				.setViewAdapter(new ArrayWheelAdapter<String>(mContext, cities));
		mViewCity.setCurrentItem(0);
		updateAreas();
	}

	private void updateAreas() {
		int pCurrent = mViewCity.getCurrentItem();
		mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
		String[] areas = mDistrictDatasMap.get(mCurrentCityName);

		if (areas == null) {
			areas = new String[] { "" };
		}
		mViewDistrict.setViewAdapter(new ArrayWheelAdapter<String>(mContext,
				areas));
		mViewDistrict.setCurrentItem(0);
	}

	@Override
	public void onChanged(WheelView wheel, int oldValue, int newValue) {
		// TODO Auto-generated method stub
		if (wheel == mViewProvince) {
			updateCities();
		} else if (wheel == mViewCity) {
			updateAreas();
		} else if (wheel == mViewDistrict) {
			mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
			mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
		}
	}

	private void showSelectedResult() {
		Toast.makeText(
				mContext,
				"锟斤拷前选锟斤拷:" + mCurrentProviceName + "," + mCurrentCityName
						+ "," + mCurrentDistrictName + "," + mCurrentZipCode,
				Toast.LENGTH_SHORT).show();
	}

}
